package com.android.newsreader;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.view.*;

/**
* An activity class for display news items
* via a web view
*/
public class ShowStory extends Activity 
{
	private RSSItemProvider mDb4oHelper = null;
	private RSSItem mRSSItem = null;
	private int mActivityTrigger = 0;

	/**
	 *  Called when the activity is first created. 
	 * */
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.showstory);
        
        String theStory = null;
        
        // Open database connection
        dbHelper();
        
        // Retrieved selected news item from Intent
        Intent startingIntent = getIntent();
        
        if (startingIntent != null)
        {
        	Bundle b = startingIntent.getBundleExtra("android.intent.extra.INTENT");
        	if (b == null)
        	{
        		theStory = getString(R.string.no_story);
        	}
        	else
    		{
        		theStory = b.getString("title") + "\n\n" + b.getString("pubdate") + "\n\n" + b.getString("description").replace('\n',' ') + "\n\nMore information:\n" + b.getString("link");
        		mRSSItem = new RSSItem();
        		mRSSItem.setTitle(b.getString("title"));
        		mRSSItem.setPubDate(b.getString("pubdate"));
        		mRSSItem.setLink(b.getString("link"));
        		mRSSItem.setDescription(b.getString("description"));
        		mRSSItem.setCategory("");
        		mActivityTrigger = b.getInt("source");
        		
    		}
        }
        else
        {
        	theStory = getString(R.string.no_story);
        
        }
        
        // Create WebView using custom web client
        WebView wb = (WebView) findViewById(R.id.webview);
        wb.setWebViewClient(new HelloWebViewClient());
        
        // Load new Item
        wb.loadUrl(mRSSItem.getLink());
        
        initialiseButtons();
        
    }
    
    /**
	 *  Sets up action listeners for buttons
	 *  on the activity 
	 * */
    private void initialiseButtons(){
    	Button backbutton = (Button) findViewById(R.id.back);
        
        backbutton.setOnClickListener(new Button.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	finish();
            }
        }); 
        
        
        if (this.mActivityTrigger == 3) {
        	Button saveButton = (Button) findViewById(R.id.save);
        	saveButton.setVisibility(android.view.View.GONE);
        	
        	Button deleteButton = (Button) findViewById(R.id.delete);
        	deleteButton.setVisibility(android.view.View.VISIBLE);
        	
            deleteButton.setOnClickListener(new Button.OnClickListener() 
            {
                public void onClick(View v) 
                {
                	if (mRSSItem != null)
						try {
							mDb4oHelper.delete(mRSSItem);
							finish();
						} catch (Exception e) {
							Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.error_del), Toast.LENGTH_LONG);
							toast.show();
						}
                }
            });
        	
        } else {
        	
        	Button deleteButton = (Button) findViewById(R.id.delete);
            deleteButton.setVisibility(android.view.View.GONE);
        	
            Button saveButton = (Button) findViewById(R.id.save);
            saveButton.setVisibility(android.view.View.VISIBLE);
            
            saveButton.setOnClickListener(new Button.OnClickListener() 
            {
                public void onClick(View v) 
                {
                	if (mRSSItem != null)
                		mDb4oHelper.store(mRSSItem);
                	finish();
                }
            });
        }

    }
    
    /**
     * Create RSSItemProvider instance
     */
     private RSSItemProvider dbHelper() {
         if (mDb4oHelper == null) {
            mDb4oHelper = RSSItemProvider.getInstance(this);
            mDb4oHelper.db();
         }
         
         return mDb4oHelper;
     } 
     
     @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		dbHelper();
	}

	/**
      * Close database before exiting the application
      */
      @Override
      protected void onPause() {
           super.onDestroy();
           if (mDb4oHelper != null)
        	   mDb4oHelper.close();
      }
      
      /**
       * Ensures external Web Browser is not called 
       *  if user clicks on links within webview
       */
      private class HelloWebViewClient extends WebViewClient {
    	    @Override
    	    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    	        view.loadUrl(url);
    	        return true;
    	    }
    	}
}
